import json

import redis

from common.config import config
from common.logger import logger


class RedisClient:
    def __init__(self):
        try:
            self.client = redis.StrictRedis(
                host=config.REDIS_HOST,
                port=config.REDIS_PORT,
                password=config.REDIS_PASSWORD,
                db=config.REDIS_DB,
                decode_responses=True
            )
            self.bus_prefix = {
                'answer': 'answer:',
            }
            logger.info("Redis 连接成功")
        except redis.RedisError as e:
            logger.error(f"Redis 连接失败: {e}")
            raise

    def set(self, key, value):
        try:
            self.client.set(key, json.dumps(value))
        except redis.RedisError as e:
            logger.error(f"Redis 存储失败: {e}")

    def get(self, key):
        try:
            data: str = self.client.get(key)
            return json.loads(data) if data else None
        except redis.RedisError as e:
            logger.error(f"Redis 获取失败: {e}")

    def get_with(self, bus, key):
        return self.get(self.get_key(bus, key))

    def set_with(self, bus, key, value):
        self.set(self.get_key(bus, key), value)

    def get_key(self, bus, key):
        if not key:
            raise ValueError("Key cannot be empty")
        prefix = self.bus_prefix[bus]
        if prefix is None:
            raise ValueError(f"Invalid bus: {bus}")
        return prefix + str(key)
